<?php
/**
 * Created by PhpStorm.
 * User: wolf
 * Date: 2018/8/27
 * Time: 15:47
 */

namespace App\Http\Controllers\MiniApp;


use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\UserCheck;
use App\Models\WeixinUser;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class OrderController extends Controller
{
    // 下单未付款的单 删除
    public function cancleNotPayOrder(Request $request)
    {
        $rules = [
            'id'=>'required|exists:orders,id',
            'token'=>'string'
        ];
        $messages = [
            'id.*'=>'请提交正确的订单号',
            'token.*'=>'请传递正确的令牌'
        ];
        $validator = Validator::make($request->all(), $rules,$messages);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        $token = $request->token;
        $order = Order::where('id',$request->id)->first();
        $WeixinUser = WeixinUser::where('token',$token)->first();
        if(!$WeixinUser){
            return show(201,"无效token！");
        }else{
            $user= UserCheck::find($WeixinUser->user_id);
            if(!$user){
                return show(201,"用户不存在！");
            }
        }

        if ($order){
            $user_id = $user->id;
            if($user_id != $order->user_id){
                return show(201,'订单不存在');
            }
            if (in_array($order->order_status,[1,-2,-3])){
                $delete = Order::where('id',$request['id'])->delete();
                if($delete){
                    return show(200,'订单删除成功');
                }else{
                    return show(201,'订单不存在');
                }
            }else{
                return show(201,'不允许删除');
            }

        }else{
            return show(201,'订单不存在');
        }
    }

    // 再来一单
    public function nextOrder(Request $request){
        $rules = [
            'id'=>'required|integer|exists:orders,id'
        ];
        $messages = [
            'id'=>'订单号有误'
        ];
        $validator = Validator::make($request->all(),$rules,$messages);
        if ($validator->fails()){
            return show(201,$validator->errors()->first());
        }
        $order = Order::where('id',$request->id)->first();
        if (!$order){
            return show(202,'暂无数据');
        }
        if ($order->order_type != '0'){
            return show(202,'暂无数据');
        }
        $order_info = OrderDetail::where('order_id',$request->id)->get([
            'dishes_id as id','dishes_name','goods_number as count','price','sell_price as discount','amount','is_attr','spec'
        ]);
        if ($order_info->isEmpty()){
            return show(202,'暂无数据');
        }
        return show(200,'获取成功',['shop_id'=>$order->shop_id,'detail'=>$order_info]);
    }
}